package cn.org.xiaosheng.utils;

import cn.org.xiaosheng.bean.RSADecodeData;
import cn.org.xiaosheng.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.Objects;

/**
 * @author XiaoSheng
 * @date 2024-05-25
 * @dec 描述
 */
public class RSAUtil {

    public final static KeyPair keyPair = RSAInitUtil.getKeyPair(2048 * 2);
    public final static String publicKey = RSAInitUtil.getPublicKeyString(keyPair);
    public final static String privateKey = RSAInitUtil.getPrivateKeyString(keyPair);
    public final static Integer timeout = 60000;


       /**
             *
             * @param sym RSA 密文
             * @param asy AES 密文
             * @param clazz 接口入参类
             * @return Object
             */
             public static <T> Object getRequestDecryption(String sym, String asy, Class<T> clazz){
                //验证密钥
                try {
                    //解密RSA
                    RSAPrivateKey rsaPrivateKey = RSAInitUtil.getRSAPrivateKeyByString(privateKey);
                    String RSAJson = RSAInitUtil.privateDecrypt(sym, rsaPrivateKey);
                    RSADecodeData rsaDecodeData = JSONObject.parseObject(RSAJson, RSADecodeData.class);
                    boolean isTimeout = Objects.nonNull(rsaDecodeData) && Objects.nonNull(rsaDecodeData.getTime()) && System.currentTimeMillis() -   rsaDecodeData.getTime() < timeout;
                    if (!isTimeout){
                        throw new ServiceException("Request timed out, please try again."); //请求超时
                    }
                    //解密AES
                    String AESJson = AES256Util.decrypt(rsaDecodeData.getKey(),asy,rsaDecodeData.getKeyVI());
                    System.out.println("AESJson: "+AESJson);
                    return JSONObject.parseObject(AESJson,clazz);
              } catch (Exception e) {
                    throw new RuntimeException("RSA decryption Exception:  " +e.getMessage()); }
      }




}
